<?php

namespace App\Kuafu\Order\Model;

use App\Kuafu\Base\Model\Traits\KfSoftDeletes;

use App\Kuafu\Base\Model\Traits\KfSplitRelation;
use App\Kuafu\Base\Model\Traits\KfUid;
use App\Kuafu\CouponExt\Enum\CouponExtEnum;
use App\Kuafu\CouponExt\Model\OrderCouponExtSplitModel;
use App\Kuafu\Customer\Model\CustomerModel;
use App\Kuafu\CustomPayment\Model\CustomPaymentModel;
use App\Kuafu\Order\Enum\CodeEnum;
use App\Kuafu\Order\Service\OrderDb;
use App\Kuafu\Order\Service\OrderTable;
use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Pay\Model\PayStreamModel;
use App\Kuafu\Pay\Model\RefundStreamModel;
use App\Kuafu\Shop\Model\Shop;
use App\Kuafu\WaiMai\Enum\WaiMaiDBEnum;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Database\Eloquent\Relations\Relation;

class OrderPayUnionSplitModel extends BaseModel
{
    use KfSplitRelation;

    protected $fillable = [
        'id', 'shopId', 'orderId', 'bizId', 'payType', 'payPrice', 'payStatus', 'createdAt', 'originalCreatedAt', 'childType', 'childTypeDesc', 'originalPrice'
    ];

    public $incrementing = false;
    public $timestamps   = false;

//    protected $connection = 'mysqlOrder';
    protected $primaryKey = 'id';

    const EXT_COUPON_MAP = [
        CouponExtEnum::EXT_PLATFORM_MEITUAN => self::PAY_TYPE_MT_GROUP_BUY,
        CouponExtEnum::EXT_PLATFORM_DOUYIN  => self::PAY_TYPE_DY_GROUP_BUY,
        CouponExtEnum::EXT_PLATFORM_XHS     => self::PAY_TYPE_XHS_COUPON_VERIFY,
    ];

    const PAY_TYPE_FY        = 1; // 富友
    const PAY_TYPE_CASH      = 2; // 现金
    const PAY_TYPE_COUPON_KF = 3; // 自己的优惠券
//    const PAY_TYPE_COUPON_EXT = 4; // 三方优惠券
    const PAY_TYPE_MT_GROUP_BUY      = 4; //美团团购
    const PAY_TYPE_TAKEOUT           = 5; //外卖
    const PAY_TYPE_DY_GROUP_BUY      = 6; //抖音团购
    const PAY_TYPE_XHS_COUPON_VERIFY = 7; //小红书券码核销
    const PAY_TYPE_DY_WAIMAI         = 10; //抖音外卖 只做显示不入库
    const PAY_TYPE_MT_WAIMAI         = 11; //美团外卖 只做显示不入库
    const PAY_TYPE_ELE_WAIMAI        = 12; //饿了么外卖 只做显示不入库
    const PAY_TYPE_DEFINE            = 100; // 自定义支付

    const PAY_TYPE_TEXT = [
        self::PAY_TYPE_FY                => '富友',
        self::PAY_TYPE_CASH              => '现金',
        self::PAY_TYPE_COUPON_KF         => '店内发券',
        self::PAY_TYPE_MT_GROUP_BUY      => '美团团购券',
        self::PAY_TYPE_DEFINE            => '自定义支付',
        self::PAY_TYPE_TAKEOUT           => '外卖',
        self::PAY_TYPE_DY_GROUP_BUY      => '抖音团购',
        self::PAY_TYPE_XHS_COUPON_VERIFY => "小红书券码核销"
    ];

    const PAY_TYPE_TEXT_NEW = [
        self::PAY_TYPE_FY                => '堂食：扫码收款',
        self::PAY_TYPE_CASH              => '堂食：现金',
        self::PAY_TYPE_DY_GROUP_BUY      => '堂食：抖音团购',
        self::PAY_TYPE_MT_GROUP_BUY      => '堂食：美团团购',
        self::PAY_TYPE_COUPON_KF         => '堂食：店内发券',
        self::PAY_TYPE_DEFINE            => '堂食：自定义支付',
        self::PAY_TYPE_MT_WAIMAI         => '美团外卖',
        self::PAY_TYPE_ELE_WAIMAI        => '饿了么外卖',
        self::PAY_TYPE_DY_WAIMAI         => '抖音外卖',
        self::PAY_TYPE_XHS_COUPON_VERIFY => "小红书券码核销"
    ];

    const PAY_STATUS_OK     = 1; // 支付成功
    const PAY_STATUS_REFUND = 2; // 退款成功

    const PAY_STATUS_TEXT = [
        self::PAY_STATUS_OK     => '支付成功',
        self::PAY_STATUS_REFUND => '退款成功',
    ];

    const WAIMAI_PAY_TYPE_MAP = [
        self::PAY_TYPE_MT_WAIMAI  => CodeEnum::SOURCE_TYPE_MT,//'美团外卖',
        self::PAY_TYPE_ELE_WAIMAI => CodeEnum::SOURCE_TYPE_ELM,//'饿了么外卖',
        self::PAY_TYPE_DY_WAIMAI  => CodeEnum::SOURCE_TYPE_DY,//'抖音外卖',
    ];

    private static $startAt, $endAt;

    public static string $tableName;
    public static string $connectionName;
    public static string $shopId;

    public static function suffix($shopId)
    {
        if (is_int($shopId) && $shopId < 0) {
            $shopId = 0;
        }

        self::$tableName      = OrderTable::orderPayUnionTableName($shopId);
        self::$connectionName = OrderDb::orderDbConnection($shopId);

        self::$shopId = $shopId;
        return new static;
    }

    public function getTable()
    {
        return self::$tableName ?? parent::getTable();
    }

    public function getConnectionName()
    {
        return self::$connectionName ?? parent::getConnectionName();
    }

    public function customPaymentsRel()
    {
        return $this->hasOne(CustomPaymentModel::class, 'id', 'payType');
    }

    public function payStreamsRel()
    {
        $tableName = (new PayStreamModel)->getBaseTable();
        $connect   = OrderDb::orderDbConnection(self::$splitShopId);

        return $this->hasOneWithTable(PayStreamModel::class, 'payNo', 'bizId', $tableName, $connect);
    }

    public function refundStreamsRel()
    {
        return $this->hasOne(RefundStreamModel::class, 'refundNo', 'bizId');
    }

    public function getPayTypeTextAttribute()
    {
        $res = self::PAY_TYPE_TEXT[$this->payType] ?? '';

        switch ($this->payType) {
            case self::PAY_TYPE_FY:
                if ($this->payStatus == self::PAY_STATUS_OK) {
                    $suffix = (string)optional($this->payStreamsRel)->payChannelChildText;
                } else {
                    $suffix = (string)optional($this->refundStreamsRel)->refundChannelChildText;
                }
                return $suffix ? $res . ' - ' . $suffix : $res;
            case $this->payType > self::PAY_TYPE_DEFINE:
                $res    = self::PAY_TYPE_TEXT[self::PAY_TYPE_DEFINE];
                $suffix = (string)optional($this->customPaymentsRel)->name;
                return $suffix ? $res . ' - ' . $suffix : $res;
        }

        return self::PAY_TYPE_TEXT[$this->payType] ?? '';
    }

    public function getPayStatusTextAttribute()
    {
        return self::PAY_STATUS_TEXT[$this->payStatus] ?? '';
    }

    /**
     * 通过支付、退款Channel，获取payType
     *
     * @param int $payChannel
     * @return int
     */
    public static function getPayTypeByPayChannel(int $payChannel): int
    {
        if ($payChannel == PayStreamModel::PAY_CHANNEL_CASH) {
            return self::PAY_TYPE_CASH;
        }

        if ($payChannel == PayStreamModel::PAY_CHANNEL_FY) {
            return self::PAY_TYPE_FY;
        }

        // 自定义支付，直接返回
        if ($payChannel >= 100) {
            return $payChannel;
        }

        return 0;
    }
}
